'use strict';

/* Controllers */

var ydylControllers = angular.module('ydylControllers', ['ngCookies','ngMd5','infinite-scroll']);

ydylControllers.controller('IndexController',
    function($scope,$cookies, $location, controllerData) {
        $scope.pages = appRoutes;
        var isRegister = $cookies.get('isRegister');
        if (isRegister && isRegister == '1') {
            $cookies.remove('isRegister');
            $location.path('/Authentication')
        }
        if(controllerData.mobile != undefined){
            $location.path('/ExpertList')
        }else{
            $location.path('/Login')
        }
    }
);
ydylControllers.controller('RegisterController',
    function($scope, $cookies, $interval, md5, myHttp) {
        $scope.agree = true;
        $scope.register = function() {
            if(!$scope.mobile || $scope.mobile == ''||!$scope.code || $scope.code == ''||!$scope.password || $scope.password == '')
            {
                alert('请填写完整资料');
                return;
            }

            //myHttp.jsonp('apiDoctor/validCode?doctormobile=' + $scope.mobile + '&code=' + $scope.code,function (codeReuslt) {
                var md5pw = md5.createHash($scope.password);
                myHttp.jsonp('apiDoctor/reg?doctormobile='+$scope.mobile+'&doctorpwd='+md5pw, function(result){
                    alert('注册成功');
                    var expireDate = new Date();
                    expireDate.setDate(expireDate.getDate() + 1);
                    $cookies.put('isRegister', "1", {'expires': expireDate});
                    location.href='#/Login?doctormobile='+$scope.mobile+'&doctorpwd='+$scope.password;
                });
           // });
        };
        $scope.codeTime = 0;
        $scope.getCode = function () {
            if($scope.codeTime>0){
                return;
            }
            if(!$scope.mobile || $scope.mobile == '')
            {
                alert('请填写完整资料');
                return;
            }
            myHttp.jsonp('apiDoctor/getValidCode?doctormobile='+$scope.mobile, function (result) {
                alert('发送成功 请查收');
                $scope.codeTime = 60;
                var interval = $interval(function() {
                    $scope.codeTime --;
                    if($scope.codeTime<=0){
                        $interval.cancel(interval);
                        interval = undefined;
                    }
                }, 1000);

                $scope.$on("$destroy", function() {
                    if (angular.isDefined(interval)) {
                        $interval.cancel(interval);
                        interval = undefined;
                    }
                });
            })
        }
    }
);

ydylControllers.controller('LoginController',
    function($scope, $cookies,$location, md5, myHttp, controllerData) {

        $scope.login = function() {
            if(!$scope.mobile || $scope.mobile == '' ||!$scope.password || $scope.password == '')
            {
                alert('请填写完整资料');
                return;
            }
            myHttp.jsonp('apiDoctor/login?doctormobile='+$scope.mobile+'&doctorpwd='+md5.createHash($scope.password), function(result){
                var token = result.items.token;
                var authentication = result.items.authentication;
                var expireDate = new Date();
                expireDate.setDate(expireDate.getDate() + 1);
                // Setting a cookie
                $cookies.put('memberToken', token, {'expires': expireDate});
                $cookies.put('memberMobile', $scope.mobile, {'expires': expireDate});
                controllerData.mobile=$scope.mobile;
                controllerData.token=token;
                if(authentication=='N'){
                    alert('您还未认证，将进入认证页面');
                    if(isWechat())
                        location.href = 'http://meirongyisheng.com.cn/ydyl/apiWeiXinAuth/wxauth?doctormobile='+$scope.mobile+'&token='+token+'&time_stamp='+new Date().getTime();
                    else
                        location.href='#/Authentication';
                }else{
                    alert('登录成功，进入专家列表');
                    if(isWechat())
                        location.href = 'http://meirongyisheng.com.cn/ydyl/apiWeiXinAuth/wxauth?doctormobile='+$scope.mobile+'&token='+token+'&time_stamp='+new Date().getTime();
                    else
                        location.href='#/ExpertList';
                }
            })
        };
        var queryMobile = $location.search().doctormobile;
        var queryPwd = $location.search().doctorpwd;
        if(queryMobile && queryPwd){
            $scope.mobile= queryMobile;
            $scope.password = queryPwd;
            $scope.login();
            return;
        }
    }
);
function isWechat(){
    return navigator.userAgent.indexOf('MicroMessenger')>0;
}

ydylControllers.controller('ForgetController',
    function($scope, md5, myHttp) {

        $scope.forget = function() {
            if(!$scope.mobile || $scope.mobile == ''||!$scope.code || $scope.code == ''||!$scope.password || $scope.password == '')
            {
                alert('请填写完整资料');
                return;
            }
            myHttp.jsonp('apiDoctor/validCode?doctormobile=' + $scope.mobile + '&code=' + $scope.code,function (codeReuslt) {
                myHttp.jsonp('apiDoctor/modifypwd?doctormobile=' + $scope.mobile + '&time_stamp=&doctorpwd=' + md5.createHash($scope.password), function (result) {
                    alert('修改成功，返回登录页面');
                    location.href = '#/Login';
                });
            });
        };

        $scope.getCode = function () {
            if(!$scope.mobile || $scope.mobile == '')
            {
                alert('请填写完整资料');
                return;
            }
            myHttp.jsonp('apiDoctor/getValidCode?doctormobile='+$scope.mobile, function (result) {
                alert('发送成功 请查收');
                console.log(this)
            })
        }
    }
);

ydylControllers.controller('MemberCenterController',
    function($scope, $cookies, $location, myHttp, controllerData) {
        var layout = document.getElementsByClassName("layout")[0];
        if (layout != undefined) {
            if (layout.offsetHeight < document.body.offsetHeight)
                layout.style.minHeight = document.body.offsetHeight + 'px';
        }

        if (checkLogin($cookies) == false) return;

        //初始化信息
        myHttp.jsonp('apiDoctor/getDoctorInfo?doctormobile='+controllerData.mobile+'&token=&time_stamp=&targetmobile='+controllerData.mobile , function (result) {
            $scope.doctor = result.items[0];
        })

        $scope.quit = function () {
            var token = $cookies.remove('memberToken');
            var mobile =$cookies.remove('memberMobile');
            controllerData.currentMember = null;
            $location.path('/Login')
        }
    }
);

ydylControllers.controller('ExpertListController',
    function($scope, myHttp, controllerData, scrollPager) {
        $scope.keyword = '';
        $scope.hospital_code = '';
        $scope.department_code = '';
        $scope.distance = '';
        $scope.goodflatrate =''

        $scope.expert = new scrollPager('apiDoctor/listAllDoctor?doctormobile='+controllerData.mobile+'&pagecount=&curPage={after}&qryname='+$scope.keyword+'&qryhospital='+$scope.hospital_code+'&qrydepartment=&qrydepartmentsub='+$scope.department_code+'&distance='+$scope.distance+'&goodflatrate='+$scope.goodflatrate+'&consultecount=');

        $scope.search = function () {
            $scope.expert.items = [];
            $scope.expert.after = 1;
            $scope.expert.changeUrl('apiDoctor/listAllDoctor?doctormobile='+controllerData.mobile+'&pagecount=&curPage={after}&qryname='+$scope.keyword+'&qryhospital='+$scope.hospital_code+'&qrydepartment=&qrydepartmentsub='+$scope.department_code+'&distance='+$scope.distance+'&goodflatrate='+$scope.goodflatrate+'&consultecount=');
            $scope.expert.nextPage();
        };
        $scope.filterIndex = 0;
        $scope.IsShowFilter = false;
        $scope.showFilter = function (type) {
			$scope.selectedItem = null;
            switch(type){
                case 1:
                    //myHttp.jsonp('apiConsultOrder/listAllHospital?doctormobile='+controllerData.mobile+'&token='+controllerData.token+'&time_stamp='+new Date().getTime() , function (result) {
						myHttp.jsonp('apiConsultOrder/listAllArea?doctormobile='+controllerData.mobile+'&token='+controllerData.token+'&time_stamp='+new Date().getTime() , function (result) {
                        $scope.filters = result.items;
                        console.log(result.items)
                    });
                    break;
                case 2:
                    myHttp.jsonp('apiConsultOrder/listAllDepartment?doctormobile='+controllerData.mobile+'&token='+controllerData.token+'&time_stamp='+new Date().getTime() , function (result) {
                        $scope.filters = result.items;
                        console.log(result.items)
                    });
                    break;
                case 3:
                    var items = [
                        {hospital_code:'1',hospital_name:'好评优先'},
                        {hospital_code:'2',hospital_name:'离我最近'}
                    ];
                    $scope.filters = items;
                    break;
                default:
                    break;
            }

            $scope.selectLevel1 = function (item) {
                $scope.selectedItem = item;
				if(item.area_name){
					myHttp.jsonp('apiConsultOrder/listAllHospital?doctormobile='+controllerData.mobile+'&token='+controllerData.token+'&time_stamp='+new Date().getTime()+'&qryarea='+item.area_code , function (result) {
						$scope.selectedItem.subnode = result.items;
					});
				}
                console.log(item);
            }

            $scope.IsShowFilter = !$scope.IsShowFilter;
            $scope.filterIndex = type;
        };
        $scope.filterClick = function (code, type) {
            switch(type) {
                case 1:
                    $scope.hospital_code = code;
                    break;
                case 2:
                    $scope.department_code = code;
                    break;
                case 3:
                    if(code == '1'){
                        $scope.goodflatrate = 'Y';
                        $scope.distance = '';
                    }else if(code == '2'){
                        $scope.goodflatrate = '';
                        $scope.distance = 'Y';
                    }else{
                        $scope.goodflatrate = '';
                        $scope.distance = '';
                    }
                    break;
                default:
                    break;
            }
            $scope.search();
            $scope.IsShowFilter = false;
        };

        // $scope.$on('$viewContentLoaded', function () {
        //     var layout = document.getElementsByClassName("layout")[0];
        //     if (layout != undefined) {
        //         if (layout.offsetHeight < document.body.offsetHeight)
        //             layout.style.height = document.body.offsetHeight + 'px';
        //     }
        //     console.log(layout.offsetHeight+','+document.body.offsetHeight)
        // });
    }
);

ydylControllers.controller('ExpertHomeController',
    function($scope, $location, $cookies, myHttp, controllerData) {
        function checkAuth(member) {
            if(member)
                if(member.authentication!='Y')
                    $location.path('/Authentication')
        }
        $scope.member = controllerData.getMember(function (member) {
            $scope.member = member;
            checkAuth(member)
        });
        checkAuth($scope.member)

        $scope.isFollow = false;
        myHttp.jsonp('apiDoctor/getDoctorInfo?doctormobile='+controllerData.mobile+'&token='+controllerData.token+'&time_stamp='+new Date().getTime()+'&targetmobile='+$location.search().mobile, function (result) {
            $scope.doctor = result.items[0];
            $scope.isFollow = $scope.doctor.follow=='Y';
        })
        $scope.follow = function () {
            //apiDoctor/follow?doctormobile=&token=&time_stamp=&targetmobile=
            if($scope.isFollow)
                myHttp.jsonp('apiDoctor/cancelfollow?doctormobile='+controllerData.mobile+'&token='+controllerData.token+'&time_stamp='+new Date().getTime()+'&targetmobile='+$location.search().mobile, function (result) {
                    $scope.isFollow = false;
                    alert('取消关注成功');
                })
            else
                myHttp.jsonp('apiDoctor/follow?doctormobile='+controllerData.mobile+'&token='+controllerData.token+'&time_stamp='+new Date().getTime()+'&targetmobile='+$location.search().mobile, function (result) {
                    $scope.isFollow = true;
                    alert('关注成功');
                })
        }
        $scope.go = function () {
            controllerData.selectedDoctors =[$scope.doctor];
            controllerData.selectedFile = [];
            location.href='#/EnquireStart';
        }
    }
);

ydylControllers.controller('EnquireStartController',
    function($scope, $location, $cookies, myHttp, controllerData) {

        $scope.member = controllerData.getMember(function (member) {
            $scope.member = member;
        });

        if($location.search().mobile) {
            myHttp.jsonp('apiDoctor/getDoctorInfo?doctormobile='+$scope.mobile+'&token=&time_stamp=&targetmobile='+$location.search().mobile , function (result) {
                $scope.doctors = [result.items[0]];
            });
        }

        $scope.purposes = [{name:'诊断',checked:false},{name:'治疗',checked:true}]
        $scope.doctors = $scope.doctors||controllerData.selectedDoctors;


        $scope.targetType = true;
        $scope.changeTargetType = function (type) {
            $scope.targetType = type;
        };

        $scope.selectedOption = controllerData.selectedPatient;
        myHttp.jsonp('apiPatient/listMyPatients?doctormobile='+controllerData.mobile+'&token='+controllerData.token+'&time_stamp='+new Date().getTime()+'&pagecount=&curPage=&qryname=', function (result) {
            $scope.patients = result.items;
            console.log(result)
        });


        $scope.hidden = true;
        $scope.hiddenScroll = false;
        var consult_id;
        $scope.go = function () {

            var checkedPurposes = [];
            for(var p in $scope.purposes){
               if($scope.purposes[p].checked)
                   checkedPurposes.push($scope.purposes[p].name)
            }
            if(checkedPurposes.length==0){
                alert('请选择一个资询目的');
                return;
            }

            var postData ={
                doctormobile:controllerData.mobile,
                consult_purpose:checkedPurposes.join(','),
                patient_id:$scope.selectedOption.patient_id,
                patient_name:$scope.selectedOption.patient_name,
                patient_age:$scope.selectedOption.patient_age,
                patient_sex:$scope.selectedOption.patient_sex,
                patient_diagnosis:$scope.selectedOption.patient_diagnosis,
                patient_illness:$scope.selectedOption.patient_illness,
                token:controllerData.token,
                time_stamp:new Date().getTime(),
                consultid:0,
                professions:$scope.doctors.map(function(e){return e.doctor_mobile}).join('|')
            };
            var api = $scope.doctors.length >1?'pubConsultMany':'pubConsultOne';
            myHttp.post('apiConsultOrder/'+api, postData, function (result) {
                consult_id = result.items[0].consult_id;
                //apiConsultOrder/notifyProfessional
                postData.consultid = consult_id;

                for(var i in controllerData.selectedFile){
                    var uploadPostData = {
                        doctormobile:postData.doctormobile,
                        token:postData.token,
                        time_stamp:new Date().getTime(),
                        consultid:postData.consultid,
                        attachment_path:controllerData.selectedFile[i]
                    };
                    myHttp.post('apiConsultOrder/uploadConsultAttachment', uploadPostData, function (result) {
                    });
                }


                myHttp.post('apiConsultOrder/notifyProfessional', postData, function (result) {
                });
            });
            $scope.hidden = false;
            $scope.hiddenScroll = true;
            controllerData.selectedPatient = null;
            scrollTo(0,0);
            //location.href='#/ExpertChoose?patientId='+$scope.selectedOption.patient_id
        };
        $scope.confirm = function () {
            //location.href='#/EnquiringCancel?patientId='+$scope.selectedOption.patient_id +'&mobile=' + $location.search().mobile;
            location.href='#/EnquiringCancel?consultId='+consult_id;
        };
        $scope.showPic = false;
        $scope.goPic = function () {
            $scope.showPic = !$scope.showPic;
        }
        $scope.confirmPic = function () {
            $scope.showPic = false;
            $scope.showAttach = false;
        }
        $scope.showAttach = false;
        $scope.goAttach = function () {
            $scope.showAttach = !$scope.showAttach;
        }

        $scope.goToDoctorList = function () {
            controllerData.selectedPatient = $scope.selectedOption;
            $location.path('ExpertChoose')
        }


        var client = new OSS.Wrapper({
            region: 'oss-cn-beijing',
            accessKeyId: 'vOGOcsubfsQHqlAX',
            accessKeySecret: 'G5tVAHUeVeNVVy7gu6ZJIc9FzcNKE9',
            bucket: '301-ydyl-upload'
        });
        var ossUrl = 'http://301-ydyl-upload.oss-cn-beijing.aliyuncs.com/';
        $scope.selectedFile = controllerData.selectedFile;

        document.getElementById('hideFile').addEventListener('change', function (e) {
            var file = e.target.files[0];
            var fileName = file.name;
            var storeAs = 'infopic/' + new Date().getTime() + fileName.substring(fileName.indexOf('.'));
            client.multipartUpload(storeAs, file).then(function (result) {
                console.log(result);

                controllerData.selectedFile.push(ossUrl + result.name);
                $scope.selectedFile = controllerData.selectedFile;
                $scope.$apply();
                reloadPic();
            }).catch(function (err) {
                console.log(err);
                alert(err);
            });
        });


        $scope.upload = function () {
            if($scope.showPic && $scope.pic>=6){
                alert('对不起，最多只能添加6张图片');
                return;
            }
            if($scope.showAttach && $scope.attach>=6){
                alert('对不起，最多只能添加6个附件');
                return;
            }
            document.getElementById('hideFile').click();
        };

        $scope.delete = function (url) {
            removeByValue(controllerData.selectedFile, url);
            $scope.selectedFile = controllerData.selectedFile;
            reloadPic();
        };

        $scope.myFilter = function (isPic) {
            return function(item) {
                var match = item.match(/(.jpg|.png|.gif|.jpeg|.bmp)/ig)
                return isPic? match : !match;
            }
        }
        function reloadPic() {
            var picCount = controllerData.selectedFile.map($scope.myFilter(true)).join('').split('.').length-1;
            $scope.pic = picCount;
            $scope.attach = controllerData.selectedFile.length-picCount;
        }
        reloadPic();

    }
);

ydylControllers.controller('ExpertChooseController',
    function($scope, $location, $cookies, myHttp, controllerData, scrollPager) {
        $scope.keyword = '';
        $scope.hospital_code = '';
        $scope.department_code = '';
        $scope.distance = '';
        $scope.goodflatrate ='';


        $scope.scrollPager = new scrollPager('apiDoctor/listAllDoctor?doctormobile='+controllerData.mobile+'&pagecount=&curPage={after}&qryname='+$scope.keyword+'&qryhospital='+$scope.hospital_code+'&qrydepartment=&qrydepartmentsub='+$scope.department_code+'&distance='+$scope.distance+'&goodflatrate='+$scope.goodflatrate+'&consultecount=');
        $scope.scrollPager.callback = function () {

            if(controllerData.selectedDoctors.length>0)
            {
                var mobiles =  controllerData.selectedDoctors.map(function(e){return e.doctor_mobile}).join(',');
                for(var i in $scope.scrollPager.items){
                    if(mobiles.indexOf($scope.scrollPager.items[i].doctor_mobile)>=0){
                        $scope.scrollPager.items[i].checked = true;
                    }
                }
            }
        }

        $scope.search = function () {
            $scope.scrollPager.items = [];
            $scope.scrollPager.after = 1;
            $scope.scrollPager.changeUrl('apiDoctor/listAllDoctor?doctormobile='+controllerData.mobile+'&pagecount=&curPage={after}&qryname='+$scope.keyword+'&qryhospital='+$scope.hospital_code+'&qrydepartment=&qrydepartmentsub='+$scope.department_code+'&distance='+$scope.distance+'&goodflatrate='+$scope.goodflatrate+'&consultecount=');
            $scope.scrollPager.nextPage();
        };

        $scope.filterIndex = 0;
        $scope.IsShowFilter = false;
        $scope.showFilter = function (type) {
            $scope.selectedItem = null;
            switch(type){
                case 1:
                    //myHttp.jsonp('apiConsultOrder/listAllHospital?doctormobile='+controllerData.mobile+'&token='+controllerData.token+'&time_stamp='+new Date().getTime() , function (result) {
                    myHttp.jsonp('apiConsultOrder/listAllArea?doctormobile='+controllerData.mobile+'&token='+controllerData.token+'&time_stamp='+new Date().getTime() , function (result) {
                        $scope.filters = result.items;
                        console.log(result.items)
                    });
                    break;
                case 2:
                    myHttp.jsonp('apiConsultOrder/listAllDepartment?doctormobile='+controllerData.mobile+'&token='+controllerData.token+'&time_stamp='+new Date().getTime() , function (result) {
                        $scope.filters = result.items;
                        console.log(result.items)
                    });
                    break;
                case 3:
                    var items = [
                        {hospital_code:'1',hospital_name:'好评优先'},
                        {hospital_code:'2',hospital_name:'离我最近'}
                    ];
                    $scope.filters = items;
                    break;
                default:
                    break;
            }

            $scope.selectLevel1 = function (item) {
                $scope.selectedItem = item;
                if(item.area_name){
                    myHttp.jsonp('apiConsultOrder/listAllHospital?doctormobile='+controllerData.mobile+'&token='+controllerData.token+'&time_stamp='+new Date().getTime()+'&qryarea='+item.area_code , function (result) {
                        $scope.selectedItem.subnode = result.items;
                    });
                }
                console.log(item);
            }

            $scope.IsShowFilter = !$scope.IsShowFilter;
            $scope.filterIndex = type;
        };
        $scope.filterClick = function (code, type) {
            switch(type) {
                case 1:
                    $scope.hospital_code = code;
                    break;
                case 2:
                    $scope.department_code = code;
                    break;
                case 3:
                    if(code == '1'){
                        $scope.goodflatrate = 'Y';
                        $scope.distance = '';
                    }else if(code == '2'){
                        $scope.goodflatrate = '';
                        $scope.distance = 'Y';
                    }else{
                        $scope.goodflatrate = '';
                        $scope.distance = '';
                    }
                    break;
                default:
                    break;
            }
            $scope.search();
            $scope.IsShowFilter = false;
        };


        $scope.itemClick = function (item) {
            item.checked = !item.checked;
        }
        $scope.go = function () {
            controllerData.selectedDoctors = [];
            console.log($scope.scrollPager.items)
            var mobiles =  controllerData.selectedDoctors.map(function(e){return e.doctor_mobile}).join(',');
            for(var i in $scope.scrollPager.items){
                if($scope.scrollPager.items[i].checked == true){
                    controllerData.selectedDoctors.push($scope.scrollPager.items[i])
                }
            }
            location.href='#/EnquireStart';
        }
    }
);

ydylControllers.controller('EnquireController',
    function($scope, $location, $cookies, $interval, myHttp, controllerData) {
        $scope.type = $location.search().type||1;
        $scope.consultId = $location.search().consultId;

        $scope.hasAnyDia=  false;
        $scope.load = function () {
            controllerData.getConsultDetail($location.search().consultId, function (result) {

                //fujian
                $scope.selectedFile = result.items[0].attachment.map(function (i) {return i.attachment_path});
                var picCount = $scope.selectedFile.map($scope.myFilter(true)).join('').split('.').length-1;
                $scope.pic = picCount;
                $scope.attach = $scope.selectedFile.length-picCount;

                for (var i in result.items[0].professions) {
                    var pro = result.items[0].professions[i];
                    if (pro.doctor_mobile == controllerData.mobile) {
                        $scope.pro = pro;
                    }
                    if(pro.doctor_state==4||pro.doctor_state==6)
                        $scope.hasAnyDia= true;
                }
            });
        };

        $scope.load();
        var interval = $interval(function() {
            $scope.load();
        }, 3000);

        $scope.showPic = false;
        $scope.goPic = function () {
            $scope.showPic = !$scope.showPic;
        }
        $scope.confirmPic = function () {
            $scope.showPic = false;
            $scope.showAttach = false;
        }
        $scope.showAttach = false;
        $scope.goAttach = function () {
            $scope.showAttach = !$scope.showAttach;
        }

        $scope.myFilter = function (isPic) {
            return function(item) {
                var match = item.match(/(.jpg|.png|.gif|.jpeg|.bmp)/ig)
                return isPic? match : !match;
            }
        }


        $scope.agree = function () {
            myHttp.jsonp('apiConsultOrder/acceptConsult?doctormobile='+controllerData.mobile+'&token='+controllerData.token+'&time_stamp=' + new Date().getTime() + '&consultid='+$location.search().consultId, function (result) {
                console.log(result);
                alert(result.msg)
                $scope.load();
            });
            //location.href='#/EnquireStart';
        };


        $scope.goToChat = function (type) {
            location.href='#/EnquireChat?consultId='+$location.search().consultId+'&from=2&type='+type;
        };

        $scope.content = '';
        $scope.hidden = true;

        $scope.write = function () {
            $scope.hidden=!$scope.hidden;
            scrollTo(0,0);
        };
        $scope.confirm = function () {
            var postData = {
                doctormobile:controllerData.mobile,
                token:controllerData.token,
                time_stamp:new Date().getTime(),
                consultid:$location.search().consultId,
                content:$scope.content
            };
                //'+controllerData.mobile+'&token='+controllerData.token+'&time_stamp=' + new Date().getTime() + '&consultid='+$location.search().consultId;
            myHttp.post('apiConsultOrder/consultDiagnosis',postData, function (result) {
                console.log(result);
                alert(result.msg);
                $scope.hidden=!$scope.hidden;
                $scope.pro.doctor_state = 4;
                $scope.load();
            });
        };

        $scope.$on("$destroy", function() {
            if (angular.isDefined(interval)) {
                $interval.cancel(interval);
                interval = undefined;
            }
        });
    }
);

ydylControllers.controller('PayController',
    function($scope, $location, $cookies, myHttp, controllerData) {
        $scope.member = controllerData.getMember(function (member) {
            $scope.member = member;
        });
        $scope.mobile = controllerData.mobile;
        $scope.consultId =$location.search().consultId;
        $scope.payMethods = [
            {'name':'balance', 'cn':'余额 剩余:'+$scope.member.doctor_remain},
            {'name':'wechat', 'cn':'微信'},
            {'name':'alipay', 'cn':'支付宝'},
            {'name':'point', 'cn':'咨询积分 剩余:'+$scope.member.doctor_point}
        ];
        $scope.selectedMethod ='balance'

        controllerData.getConsultDetail($location.search().consultId, function (result) {
            for(var i in result.items[0].professions){
                var pro = result.items[0].professions[i];
                if(pro.doctor_mobile == $location.search().mobile){
                    $scope.pro = pro;
                    break;
                }
            }
        });

        $scope.goToPayForAnother = function () {
            $location.url('/PayForAnother?consultId=' + $location.search().consultId+'&money='+$scope.pro.paymoney+'&mobile='+$location.search().mobile)
        }


        $scope.selectPay = function (name) {
            $scope.selectedMethod = name;
        }
        $scope.hidden = true;
        $scope.show = function () {
            $scope.hidden = false;
            scrollTo(0,0);
        }
        $scope.pay = function () {
            $scope.hidden = true;
            switch($scope.selectedMethod){
                case 'balance':
                    myHttp.jsonp('apiDoctor/outfinance?doctormobile=' + controllerData.mobile + '&token=' + controllerData.token + '&time_stamp=' + new Date().getTime() + '&money='+$scope.pro.paymoney+'&targetmobile='+$location.search().mobile+'&consultid=' + $location.search().consultId, function (result) {
                        console.log(result);
                        alert(result.msg);
                        location.href = '#/EnquiringCancel?consultId=' + $location.search().consultId
                    });
                    break;
                case 'point':
                    myHttp.jsonp('apiDoctor/outpoint?doctormobile=' + controllerData.mobile + '&token=' + controllerData.token + '&time_stamp=' + new Date().getTime() + '&point='+$scope.pro.paymoney+'&targetmobile='+$location.search().mobile+'&consultid=' + $location.search().consultId, function (result) {
                        console.log(result);
                        alert(result.msg);
                        location.href = '#/EnquiringCancel?consultId=' + $location.search().consultId
                    });
                    break;
                case 'wechat':
                    myHttp.jsonp('apiWeiXin/jsPay?doctormobile=' + controllerData.mobile + '&token=' + controllerData.token + '&time_stamp=' + new Date().getTime() + '&money='+$scope.pro.paymoney+'&targetmobile='+$location.search().mobile+'&consultid=' + $location.search().consultId, function (result) {
                        console.log(result.items.appId);
                        var onBridgeReady = function () {
                            WeixinJSBridge.invoke(
                                'getBrandWCPayRequest', {
                                    "appId": result.items.appId,     //公众号名称，由商户传入
                                    "timeStamp": result.items.timeStamp,         //时间戳，自1970年以来的秒数
                                    "nonceStr": result.items.nonceStr, //随机串
                                    "package": result.items.package,
                                    "signType": result.items.signType,         //微信签名方式：
                                    "paySign": result.items.paySign //微信签名
                                },
                                function (res) {
                                    if (res.err_msg == "get_brand_wcpay_request:ok") {
                                        alert('支付成功');
                                        location.href = '#/EnquiringCancel?consultId=' + $location.search().consultId
                                    }     // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
                                }
                            );
                        };
                        if (typeof WeixinJSBridge == "undefined") {
                            if (document.addEventListener) {
                                document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                            } else if (document.attachEvent) {
                                document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                            }
                        } else {
                            onBridgeReady();
                        }
                    });

                    break;
                default:
                        alert('未开放');
                    break;
            }
        }
    }
);


ydylControllers.controller('PayForAnotherController',
    function($scope, $location, $cookies, myHttp, controllerData) {
        $scope.money = $location.search().money;
        myHttp.jsonp('apiWeiXin/scanCodePay?doctormobile='+controllerData.mobile+'&token='+controllerData.token+'&time_stamp='+new Date().getTime()+'&targetmobile='+$location.search().mobile+'&consultid='+$location.search().consultId+'&money='+$location.search().money, function (result) {
            $scope.qrcode = result.items.qrcodeurl;
            $scope.outtradeno = result.items.outtradeno;
        });
    }
);

ydylControllers.controller('EnquireChatController',
    function($scope, $location, $cookies, myHttp, controllerData) {
        var layout = document.getElementsByClassName("layout")[0];
        if (layout != undefined) {
            if (layout.offsetHeight < document.body.offsetHeight) {
                layout.style.minHeight = document.body.offsetHeight + 'px';
            }
        }
        $scope.consultId = $location.search().consultId;

        $scope.readonly = $location.search().type=='2';
        $scope.chatList = [];

        var callback = function (result) {
            RongIMClient.init("x4vkb1qpvafkk");

            // 设置连接监听状态 （ status 标识当前连接状态）
            // 连接状态监听器
            RongIMClient.setConnectionStatusListener({
                onChanged: function (status) {
                    switch (status) {
                        //链接成功
                        case RongIMLib.ConnectionStatus.CONNECTED:
                            console.log('链接成功');
                            break;
                        //正在链接
                        case RongIMLib.ConnectionStatus.CONNECTING:
                            console.log('正在链接');
                            break;
                        //重新链接
                        case RongIMLib.ConnectionStatus.DISCONNECTED:
                            console.log('断开连接');
                            break;
                        //其他设备登陆
                        case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
                            console.log('其他设备登陆');
                            break;
                        //网络不可用
                        case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
                            console.log('网络不可用');
                            break;
                    }
                }
            });

            // 消息监听器
            RongIMClient.setOnReceiveMessageListener({
                // 接收到的消息
                onReceived: function (message) {
                    // 判断消息类型
                    console.log(message);
                    switch (message.messageType) {
                        case RongIMClient.MessageType.TextMessage:
                            // 发送的消息内容将会被打印
                            $scope.chatList.push({
                                name: message.senderUserId,
                                isMine: false,
                                isImage:false,
                                message: message.content.content
                            });
                            $scope.$apply();

                            break;
                        case RongIMLib.RongIMClient.MessageType.ImageMessage:
                            $scope.chatList.push({
                                name: message.senderUserId,
                                isMine: false,
                                isImage:true,
                                message: message.content.content
                            });
                            $scope.$apply();
                            break;
                        default:
                            break;
                    }
                }
            });

            myHttp.jsonp('apiRongCloud/getRongCloudToken?doctormobile=' + controllerData.mobile + '&token=' + controllerData.token + '&time_stamp=' + new Date().getTime(), function (result) {
                var token = result.items.token;
                RongIMClient.connect(token, {
                    onSuccess: function (userId) {
                        console.log("connect userid " + userId)
                        if ($scope.info.discussion_id) {
                            var targetId = $scope.info.discussion_id; // 想获取自己和谁的历史消息，targetId 赋值为对方的 Id。
                            console.log('开始获取历史消息' + targetId)
                            myHttp.jsonp('apiRongCloud/getHisRongCloudMsg?doctormobile=' + controllerData.mobile + '&token=' + controllerData.token + '&time_stamp=' + new Date().getTime()+'&consultid='+$location.search().consultId, function (result) {
                                console.log(result);
                                for(var i = result.items.length-1;i>=0;i--){
                                    var message = result.items[i];
                                    var isExist = false;
                                    for(var j = 0; j < $scope.chatList.length; j++){
                                        if($scope.chatList[j].message == message.content){
                                            isExist = true;
                                            break;
                                        }
                                    }
                                    if(!isExist)
                                        $scope.chatList.push({
                                            name: message.fromUserId,
                                            isMine: controllerData.mobile == message.fromUserId,
                                            isImage:message.objectName == 'RC:ImgMsg',
                                            message: message.content
                                        });
                                }
                                //scrollTo(0,document.body.scrollHeight);
                            });
                        } else {
                            var discussionName = "讨论组名称"+$location.search().consultId; // 名称自定义
                            var userIds = $scope.info.professions.map(function (a) {
                                return a.doctor_mobile
                            });
                            userIds.push($scope.info.doctor_mobile);
                            userIds.push($location.search().consultId);
                            console.log('开始创建讨论组' + userIds)
                            RongIMClient.getInstance().createDiscussion(discussionName, userIds, {
                                onSuccess: function (discussionId) {
                                    $scope.info.discussion_id = discussionId;
                                    myHttp.jsonp('apiConsultOrder/saveDiscussionid?doctormobile=' + controllerData.mobile + '&token=' + controllerData.token + '&time_stamp=' + new Date().getTime() + '&discussion_id=' + discussionId + '&consult_id=' + $location.search().consultId, function () {

                                    });
                                }
                            })
                        }
                    },
                    onError: function (errorCode) {
                        var info = '';
                        switch (errorCode) {
                            case RongIMLib.ErrorCode.TIMEOUT:
                                info = '超时';
                                RongIMLib.RongIMClient.reconnect({
                                    onSuccess: function(){
                                        //重连成功
                                        console.info('重连成功');
                                    },
                                    onError: function(){
                                        //重连失败
                                        console.info('重连失败');
                                    }
                                });
                                break;
                            case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                                info = '未知错误';
                                break;
                            case RongIMLib.ErrorCode.UNACCEPTABLE_PaROTOCOL_VERSION:
                                info = '不可接受的协议版本';
                                break;
                            case RongIMLib.ErrorCode.IDENTIFIER_REJECTED:
                                info = 'appkey不正确';
                                break;
                            case RongIMLib.ErrorCode.SERVER_UNAVAILABLE:
                                info = '服务器不可用';
                                break;
                        }
                        //console.log(errorCode);
                    }
                });
            });
        }

        $scope.sendImage = function () {
            document.getElementById('hideFile').click();
        }

        // var client = new OSS.Wrapper({
        //     region: 'oss-cn-beijing',
        //     accessKeyId: 'vOGOcsubfsQHqlAX',
        //     accessKeySecret: 'G5tVAHUeVeNVVy7gu6ZJIc9FzcNKE9',
        //     bucket: '301-ydyl-upload'
        // });
        // var ossUrl = 'http://301-ydyl-upload.oss-cn-beijing.aliyuncs.com/';
        // $scope.selectedFile = controllerData.selectedFile;
        //
        // document.getElementById('hideFile').addEventListener('change', function (e) {
        //     var file = e.target.files[0];
        //     var fileName = file.name;
        //     var storeAs = 'infopic/message/' + new Date().getTime() + fileName.substring(fileName.indexOf('.'));
        //     client.multipartUpload(storeAs, file).then(function (result) {
        //         console.log(result);
        //         var targetId = $scope.info.discussion_id;
        //
        //         var msg = new RongIMLib.ImageMessage({content: '', extra: targetId, imageUri:ossUrl + result.name});
        //         RongIMLib.RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.DISCUSSION, targetId, msg, {
        //             onSuccess: function(message) {
        //                 console.log(message);
        //                 $scope.chatList.push({name: message.senderUserId, isMine: true, message: base64Message, isImage:true});
        //                 $scope.$apply();
        //                 console.log("SendImageMessage Successfully");
        //             },
        //             onError: function (errorCode,message) {
        //                 console.log('SendImageMessage, errorcode::' + errorCode);
        //             }
        //         });
        //     }).catch(function (err) {
        //         console.log(err);
        //         alert(err);
        //     });
        // });

        document.getElementById('hideFile').addEventListener('change', function (e) {
            var file = e.target.files[0];
            var fileName = file.name;

            var reader = new FileReader();
            reader.onload = function(processEvent){
                var base64Message = processEvent.target.result;
                var targetId = $scope.info.discussion_id;

                var msg = new RongIMLib.ImageMessage({content: base64Message, extra: targetId, imageUri:''});
                RongIMLib.RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.DISCUSSION, targetId, msg, {
                    onSuccess: function(message) {
                        console.log(message);
                        $scope.chatList.push({name: message.senderUserId, isMine: true, message: base64Message, isImage:true});
                        $scope.$apply();
                        console.log("SendImageMessage Successfully");
                    },
                    onError: function (errorCode,message) {
                        console.log('SendImageMessage, errorcode::' + errorCode);
                    }
                });

            };
            reader.readAsDataURL(file);

        });

        $scope.sendMessage = function () {
            var text = $scope.messageText;
            $scope.messageText = null;
            var targetId = $scope.info.discussion_id;
            var msg = new RongIMLib.TextMessage({content: text, extra: targetId});
            RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.DISCUSSION, targetId, msg, {
                    onSuccess: function (message) {
                        //message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
                        $scope.chatList.push({name: message.senderUserId, isMine: true, message: text});
                        $scope.$apply();
                        console.log(message)
                        console.log("Send successfully");
                    },
                    onError: function (errorCode, message) {
                        var info = '';
                        switch (errorCode) {
                            case RongIMLib.ErrorCode.TIMEOUT:
                                info = '超时';
                                break;
                            case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                                info = '未知错误';
                                break;
                            case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
                                info = '在黑名单中，无法向对方发送消息';
                                break;
                            case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
                                info = '不在讨论组中';
                                break;
                            case RongIMLib.ErrorCode.NOT_IN_GROUP:
                                info = '不在群组中';
                                break;
                            case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
                                info = '不在聊天室中';
                                break;
                            default :
                                info = x;
                                break;
                        }
                        console.log('发送失败:' + info);
                    }
                }
            );
        }

        //if(controllerData.currentConsult == null)
        controllerData.getConsultDetail($location.search().consultId, callback);
        //else
        //    $scope.info = controllerData.currentConsult;


        $scope.finish = function () {
            if (confirm('确定要结束咨询吗？')) {
                switch ($location.search().from) {
                    case '1':
                        myHttp.jsonp('apiConsultOrder/finishConsult?doctormobile=' + controllerData.mobile + '&token=' + controllerData.token + '&time_stamp=' + new Date().getTime() + '&consultid=' + $location.search().consultId, function (result) {
                            console.log(result);
                            alert(result.msg);
                            location.href = '#/EnquiringCancel?consultId=' + $location.search().consultId
                        });
                        break;
                    case '2':
                        myHttp.jsonp('apiConsultOrder/professionfinishConsult?doctormobile=' + controllerData.mobile + '&token=' + controllerData.token + '&time_stamp=' + new Date().getTime() + '&consultid=' + $location.search().consultId, function (result) {
                            console.log(result);
                            alert(result.msg);
                            location.href = '#/Enquire?consultId=' + $location.search().consultId
                        });
                        break;
                    default:
                        break;
                }
            }
        };

    }
);

ydylControllers.controller('EnquiringCancelController',
    function($scope, $location, $cookies,$interval, controllerData, myHttp) {

        $scope.member = controllerData.getMember(function (member) {
            $scope.member = member;
        });
        $scope.partientId = $location.search().patientId;
        $scope.cancelable = false;
        $scope.consultId = $location.search().consultId;

        var remaintimes = 1001;
        var time1970 = (new Date("1971-01-01")).getTime();

        $scope.pay = function (mobile) {
            location.href = '#/Pay?consultId='+$location.search().consultId +'&mobile='+mobile;
        };
        $scope.hidden = true;
        $scope.stars= [true,true,true,false,false];
        $scope.starsCount = 1;
        $scope.evaluate = function (mobile) {
            $scope.currentMobile = mobile;
            $scope.hidden = false;
            scrollTo(0,0);
        };
        $scope.staring = function (index) {
            $scope.starsCount = index +1;
            $scope.stars= [true,false,false,false,false];
            for(var i=0;i<=index;i++)
                $scope.stars[i]=true;
        };

        //取消
        $scope.cancelConfirm = function () {
            myHttp.jsonp('apiConsultOrder/cancelConsult?doctormobile=' + controllerData.mobile + '&token=' + controllerData.token + '&time_stamp=' + new Date().getTime() + '&consultid=' + $location.search().consultId, function (result) {
                alert(result.msg);
            });
        }
        $scope.confirm = function () {
            var postData = {
                doctormobile: controllerData.mobile,
                consultid: $location.search().consultId,
                targetmobile: $scope.currentMobile,
                comment_content: $scope.starsCount,
                score: $scope.starsCount,
                token: controllerData.token,
                time_stamp: new Date().getTime()
            };
            myHttp.post('apiConsultOrder/doctorcomments' , postData, function (result) {
                alert(result.msg);
                $scope.load();
                $scope.hidden = true;
            })
        };
        $scope.state = 0;
        $scope.load = function () {
            controllerData.getConsultDetail($location.search().consultId, function (result) {
                remaintimes = result.items[0].remaintimes;
                $scope.info.remaintimes = new Date(time1970+remaintimes);
                $scope.selectedFile = result.items[0].attachment.map(function (i) {return i.attachment_path});
                var picCount = $scope.selectedFile.map($scope.myFilter(true)).join('').split('.').length-1;
                $scope.pic = picCount;
                $scope.attach = $scope.selectedFile.length-picCount;
                for (var i in result.items[0].professions) {
                    var pro = result.items[0].professions[i];
                    if (pro.doctor_state > $scope.state) {
                        $scope.state = pro.doctor_state
                    }
                }
            });
        };

        $scope.checkState1 = function () {
            if($scope.info)
            for (var i in $scope.info.professions) {
                var pro = $scope.info.professions[i];
                if (pro.doctor_state != 1) {
                    return false;
                }
            }
            return true;
        }
        $scope.checkState3 = function () {
            if($scope.info) {

                for (var i in $scope.info.professions) {
                    var pro = $scope.info.professions[i];
                    if (pro.doctor_state == 3 || pro.doctor_state == 5) {
                        return true;
                    }
                }
            }
            return false;
        }

        $scope.checkState4 = function () {
            if($scope.info) {
                    for (var i in $scope.info.professions) {
                        var pro = $scope.info.professions[i];
                        if (pro.doctor_state == 4||pro.doctor_state == 6) {
                            return true;
                        }
                    }
            }
            return false;
        }

        $scope.showPic = false;
        $scope.goPic = function () {
            $scope.showPic = !$scope.showPic;
        }
        $scope.confirmPic = function () {
            $scope.showPic = false;
            $scope.showAttach = false;
        }
        $scope.showAttach = false;
        $scope.goAttach = function () {
            $scope.showAttach = !$scope.showAttach;
        }

        $scope.myFilter = function (isPic) {
            return function(item) {
                var match = item.match(/(.jpg|.png|.gif|.jpeg|.bmp)/ig)
                return isPic? match : !match;
            }
        }

        $scope.goToChat = function () {
            var  type = 2;
            for (var i in $scope.info.professions) {
                var pro = $scope.info.professions[i];
                if (pro.doctor_state == 3) {
                    type = 1
                    break;
                }
            }
            location.href='#/EnquireChat?consultId='+$location.search().consultId+'&from=1&type='+type;
        };

        $scope.load();
        var interval = $interval(function() {
            $scope.load();
        }, 3000);

        var interval2 = $interval(function () {
            remaintimes = remaintimes-1000;
            if(remaintimes<=0) {
                $scope.cancelable = true;
                //$scope.$apply();
                $interval.cancel(interval2);
            }else{
                $scope.info.remaintimes = new Date(time1970+remaintimes);
                //$scope.$apply();
            }
            //console.log(time)
        }, 1000);

        $scope.$on("$destroy", function() {
            if (angular.isDefined(interval)) {
                $interval.cancel(interval);
                interval = undefined;
            }

            if (angular.isDefined(interval2)) {
                $interval.cancel(interval2);
                interval2 = undefined;
            }
        });
    }
);

ydylControllers.controller('AuthenticationController',
    function($scope, $location, $cookies, myHttp) {
        var client = new OSS.Wrapper({
            region: 'oss-cn-beijing',
            accessKeyId: 'vOGOcsubfsQHqlAX',
            accessKeySecret: 'G5tVAHUeVeNVVy7gu6ZJIc9FzcNKE9',
            bucket: '301-ydyl-upload'
        });
        var ossUrl = 'http://301-ydyl-upload.oss-cn-beijing.aliyuncs.com/';


        document.getElementById('certInput').addEventListener('change', function (e) {
            var file = e.target.files[0];
            var fileName = file.name;
            var storeAs = 'infopic/' + new Date().getTime() + fileName.substring(fileName.indexOf('.'));
            client.multipartUpload(storeAs, file).then(function (result) {
                console.log(result);
                $scope.doctor.doctor_certificate = ossUrl + result.name;
                $scope.$apply();
            }).catch(function (err) {
                console.log(err);
            });

        });

        $scope.uploadAvatar = function () {
            document.getElementById('avatarInput').click();
        };
        $scope.uploadCert = function () {
            document.getElementById('certInput').click();
        }

        var token =$cookies.get('memberToken');
        var mobile =$cookies.get('memberMobile');
        //初始化信息
        myHttp.jsonp('apiDoctor/getDoctorInfo?doctormobile='+mobile+'&token=&time_stamp=&targetmobile='+mobile , function (result) {
            $scope.doctor = result.items[0];
            $scope.currentDepartment = $scope.doctor.doctor_department;
            $scope.doctor.doctor_department = $scope.doctor.doctor_department_code;
            $scope.currentHospital = $scope.doctor.doctor_hospital;
            $scope.doctor.doctor_hospital = $scope.doctor.doctor_hospital_code;
            $scope.currentQualification = $scope.doctor.doctor_qualifications;
            $scope.doctor.doctor_qualifications = $scope.doctor.doctor_qualifications_code;
        })

        //科室
        $scope.showDepartment = false;
        $scope.currentDepartment = undefined;
        $scope.chooseDepartment  = function () {
            $scope.showDepartment = !$scope.showDepartment;
			$scope.subDepartments=null;
			
            myHttp.jsonp('apiConsultOrder/listAllDepartment?doctormobile='+mobile+'&token='+token+'&time_stamp='+new Date().getTime() , function (result) {
                $scope.departments=result.items
            })
        }
        $scope.closeDepartment  = function (d) {
            $scope.doctor.doctor_department_sub = d.department_code;
            $scope.currentDepartment = d.department_name;
            $scope.showDepartment = !$scope.showDepartment;
        }
		$scope.step1Department = function (d) {
            $scope.doctor.doctor_department = d.department_code;
            $scope.departments = null;
			$scope.subDepartments = d.subnode;
        }

        //医院
        $scope.showHospital = false;
        $scope.currentHospital = undefined;
        $scope.chooseHospital  = function () {
            $scope.showHospital = !$scope.showHospital;
			$scope.hospitals = null;
			myHttp.jsonp('apiConsultOrder/listAllArea?doctormobile='+mobile+'&token='+token+'&time_stamp='+new Date().getTime() , function (result) {
                $scope.areas=result.items
            })
            //myHttp.jsonp('apiConsultOrder/listAllHospital?doctormobile='+mobile+'&token='+token+'&time_stamp='+new Date().getTime() , function (result) {
            //    $scope.hospitals=result.items
            //})
        }
		$scope.step1Hospital = function (d) {
			$scope.areas= null;
			myHttp.jsonp('apiConsultOrder/listAllHospital?doctormobile='+mobile+'&token='+token+'&time_stamp='+new Date().getTime()+'&qryarea='+d.area_code , function (result) {
                $scope.hospitals=result.items
            })
		}
        $scope.closeHospital = function (d) {
            $scope.doctor.doctor_hospital = d.hospital_code;
            $scope.currentHospital = d.hospital_name;
            $scope.showHospital = !$scope.showHospital;
        }

        //资质 qualification
        $scope.showQualification = false;
        $scope.currentQualification = undefined;
        $scope.chooseQualification  = function () {
            $scope.showQualification = !$scope.showQualification;

            myHttp.jsonp('apiDoctor/listAllQualification?doctormobile='+mobile+'&token='+token+'&time_stamp='+new Date().getTime() , function (result) {
                $scope.qualifications=result.items
            })
        }
        $scope.closeQualification  = function (d) {
            $scope.doctor.doctor_qualifications = d.qualification_code;
            $scope.currentQualification = d.qualification_name;
            $scope.showQualification = !$scope.showQualification;
        }

        //保存
        $scope.save = function () {
            //var params = {doctormobile:'',doctor_name:'',doctor_headphoto:'',doctor_certificate:'',doctor_certificate_code:'',doctor_hospital:'', doctor_department:'',doctor_department_sub:'',doctor_qualifications:'',doctor_goodat:'',doctor_brief:'',isprofession:'',token:'',time_stamp:''};
            if(!$scope.doctor.doctor_name || $scope.doctor.doctor_name == ''){
                alert('请填写姓名');
                return;
            }
            if(!$scope.doctor.doctor_hospital || $scope.doctor.doctor_hospital == ''){
                alert('请选择医院');
                return;
            }
            if(!$scope.doctor.doctor_certificate || $scope.doctor.doctor_certificate == ''){
                alert('请上传证书');
                return;
            }
            $scope.doctor.token = token;
            $scope.doctor.time_stamp = new Date().getTime();
            $scope.doctor.doctormobile = $scope.doctor.doctor_mobile;
            myHttp.post('apiDoctor/modifyDoctorInfo',$scope.doctor, function (result) {
                alert('修改成功')
                $location.path('MemberCenter')
            })
        }

    }
);


ydylControllers.controller('MemberProfileController',
    function($scope, $location, $cookies, myHttp, controllerData) {


        //初始化信息
        myHttp.jsonp('apiDoctor/getDoctorInfo?doctormobile='+controllerData.mobile+'&token=&time_stamp=&targetmobile='+controllerData.mobile , function (result) {
            $scope.doctor = result.items[0];
            $scope.currentDepartment = $scope.doctor.doctor_department_sub;
            $scope.doctor.doctor_department = $scope.doctor.doctor_department_sub_code;
            $scope.currentHospital = $scope.doctor.doctor_hospital;
            $scope.doctor.doctor_hospital = $scope.doctor.doctor_hospital_code;
            $scope.currentQualification = $scope.doctor.doctor_qualifications;
            $scope.doctor.doctor_qualifications = $scope.doctor.doctor_qualifications_code;
        })

        //科室
        $scope.showDepartment = false;
        $scope.currentDepartment = undefined;

        //医院
        $scope.showHospital = false;
        $scope.currentHospital = undefined;


        //资质 qualification
        $scope.showQualification = false;
        $scope.currentQualification = undefined;

        //保存
        $scope.save = function () {
            //var params = {doctormobile:'',doctor_name:'',doctor_headphoto:'',doctor_certificate:'',doctor_certificate_code:'',doctor_hospital:'', doctor_department:'',doctor_department_sub:'',doctor_qualifications:'',doctor_goodat:'',doctor_brief:'',isprofession:'',token:'',time_stamp:''};
            $scope.doctor.token = controllerData.token;
            $scope.doctor.time_stamp = new Date().getTime();
            $scope.doctor.doctormobile = $scope.doctor.doctor_mobile;
            myHttp.post('apiDoctor/modifyDoctorInfo',$scope.doctor, function (result) {
                alert('修改成功');
                $location.path('MemberCenter')
            })
        }

    }
);

ydylControllers.controller('PointDetailsController',
    function($scope, $location, $cookies, myHttp,controllerData) {

        myHttp.jsonp('apiDoctor/mypoint?doctormobile='+controllerData.mobile+'&token='+controllerData.token+'&time_stamp='+new Date().getTime()+'&pagecount=&curPage=', function (result) {
            $scope.items = result.items;
            console.log(result.items)
        })

    }
);


ydylControllers.controller('EnquiringProfileController',
    function($scope, $location, $cookies, myHttp, controllerData) {
        if($location.search().consultId){
            myHttp.jsonp('apiConsultOrder/consultDetail?doctormobile='+controllerData.mobile+'&token='+controllerData.token+'&time_stamp='+new Date().getTime()+'&consultid='+$location.search().consultId, function (result) {
                if(result.items[0].patient_id){
                    myHttp.jsonp('apiPatient/getPatientDetail?doctormobile=' + controllerData.mobile + '&token=' + controllerData.token + '&time_stamp=' + new Date().getTime() + '&patientid=' + result.items[0].patient_id, function (result) {
                        $scope.patient = result.items;
                        console.log(result.items)

                    })
                }else {
                    $scope.patient = {};
                    $scope.patient.patient_name = result.items[0].patient_name;
                    $scope.patient.patient_age = result.items[0].patient_age;
                    $scope.patient.patient_sex = result.items[0].patient_sex;
                    $scope.patient.patient_diagnosis = result.items[0].patient_diagnosis;
                    $scope.patient.patient_bloodtype = result.items[0].patient_bloodtype;
                    $scope.patient.patient_genetic_history = result.items[0].patient_genetic_history;
                }
            })
        }else{
            myHttp.jsonp('apiPatient/getPatientDetail?doctormobile=' + controllerData.mobile + '&token=' + controllerData.token + '&time_stamp=' + new Date().getTime() + '&patientid=' + $location.search().id, function (result) {
                $scope.patient = result.items;
                console.log(result.items)
            })
        }
        
        $scope.goDicom = function () {
            location.href = '#/Dicom?code='+$scope.patient.patient_code;
            //$location.path('/Dicom?code='+$scope.patient.patient_code);
        }
    }
);


ydylControllers.controller('DicomController',
    function($scope, $location, $cookies, myHttp, controllerData) {

        myHttp.jsonp('apiPatient/getPatientOtherPics?doctormobile=' + controllerData.mobile + '&token=' + controllerData.token + '&time_stamp=' + new Date().getTime() + '&patient_code=' + $location.search().code, function (result) {
            $scope.items = result.items;
            for(var key in $scope.items){
                var item = $scope.items[key];
                if(item.study_date){
                    var study_date = item.study_date.substring(0,16);
                    study_date = study_date.replace(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(.*)/,"$1-$2-$3 $4:$5:$6");
                    item.study_date = study_date;
                }
            }
            console.log(result.items)
        })

    }
);

ydylControllers.controller('OrderFromMeController',
    function($scope, $location, myHttp,controllerData, scrollPager) {
        function checkAuth(member) {
            if(member)
                if(member.authentication!='Y')
                    $location.path('/Authentication')
        }
        $scope.member = controllerData.getMember(function (member) {
            $scope.member = member;
            checkAuth(member)
        });
        checkAuth($scope.member)

        $scope.filterId='';
        $scope.filterIndex = 2;
        $scope.isShowFilter = false;
        $scope.showFilter = function (type) {
            switch(type){

                case 3:
                    var items = [
                        {id:'1',name:'待接受'},
                        {id:'2',name:'待付款'},
                        {id:'3',name:'咨询中'},
                        {id:'4',name:'待评价'},
                        {id:'5',name:'已完成'},
                        {id:'6',name:'已取消'}
                    ];
                    $scope.filters = items;
                    break;
                default:
                    break;
            }

            $scope.isShowFilter = !$scope.isShowFilter;
            $scope.filterIndex = type;
        };

        $scope.filterClick = function (id, type) {
            switch(type) {
                case 1:
                    break;
                case 2:
                    break;
                case 3:
                    $scope.filterId =  id;
                    break;
                default:
                    break;
            }
            $scope.search();
            $scope.isShowFilter = false;
        };


        $scope.scrollPager = new scrollPager('apiConsultOrder/myConsult?doctormobile='+controllerData.mobile+'&state='+$scope.filterId+'&token='+controllerData.token+'&time_stamp='+new Date().getTime()+'&pagecount=&curPage={after}&years=');

        $scope.search = function () {
            $scope.scrollPager.items = [];
            $scope.scrollPager.after = 1;
            $scope.scrollPager.changeUrl('apiConsultOrder/myConsult?doctormobile='+controllerData.mobile+'&state='+$scope.filterId+'&token='+controllerData.token+'&time_stamp='+new Date().getTime()+'&pagecount=&curPage={after}&years=');
            $scope.scrollPager.nextPage();
        };
    }
);
ydylControllers.controller('OrderToMeController',
    function($scope, $location, myHttp, controllerData, scrollPager) {
        $scope.filterId='';
        $scope.filterIndex = 2;
        $scope.isShowFilter = false;
        $scope.showFilter = function (type) {
            switch(type){

                case 3:
                    var items = [
                        {id:'1',name:'待接受'},
                        {id:'2',name:'待付款'},
                        {id:'3',name:'咨询中'},
                        {id:'4',name:'待评价'},
                        {id:'5',name:'已完成'},
                        {id:'6',name:'已取消'}
                    ];
                    $scope.filters = items;
                    break;
                default:
                    break;
            }

            $scope.isShowFilter = !$scope.isShowFilter;
            $scope.filterIndex = type;
        };

        $scope.filterClick = function (id, type) {
            switch(type) {
                case 1:
                    break;
                case 2:
                    break;
                case 3:
                    $scope.filterId =  id;
                    break;
                default:
                    break;
            }
            $scope.search();
            $scope.isShowFilter = false;
        };


        $scope.scrollPager = new scrollPager('apiConsultOrder/consultMe?doctormobile='+controllerData.mobile+'&state='+$scope.filterId+'&token='+controllerData.token+'&time_stamp='+new Date().getTime()+'&pagecount=&curPage={after}&years=');

        $scope.search = function () {
            $scope.scrollPager.items = [];
            $scope.scrollPager.after = 1;
            $scope.scrollPager.changeUrl('apiConsultOrder/consultMe?doctormobile='+controllerData.mobile+'&state='+$scope.filterId+'&token='+controllerData.token+'&time_stamp='+new Date().getTime()+'&pagecount=&curPage={after}&years=');
            $scope.scrollPager.nextPage();
        };

    }
);

ydylControllers.controller('DiagnosisListController',
    function($scope,$location, myHttp,controllerData) {
        myHttp.jsonp('apiConsultOrder/listConsultDiagnosis?doctormobile='+controllerData.mobile+'&token='+controllerData.token+'&time_stamp='+new Date().getTime()+'&consultid='+$location.search().consultId, function (result) {
            $scope.items = result.items;
            console.log(result.items)
        });

    }
);
ydylControllers.controller('YxjtListController',
    function($scope,$cookies,$location, myHttp01, controllerData, scrollPager01) {

        function checkAuth(member) {
            if(member)
                if(member.authentication!='Y'){
                    $location.path('/Authentication');
                    return false;
                }

        }
        $scope.member = controllerData.getMember(function (member) {
            $scope.member = member;
            checkAuth(member);
        });
        checkAuth($scope.member);



        var token =$cookies.get('memberToken');
        $scope.mobile =$cookies.get('memberMobile');

        $scope.filterStatus = 'C';

        var getUrl = function(){

            var url = 'SysDirectbroadcast/list' +
                '?token='+ token+
                '&doctormobile='+$scope.mobile+
                '&time_stamp=' + new Date().getTime()+
                '&qstatus='+ $scope.filterStatus +
                '&pagecount=&curPage={after}' ;


            if($scope.filterStatus == 'E'){

                url = 'SysDirectbroadcast/listCourseware' +
                    '?token='+ token+
                    '&doctormobile='+$scope.mobile+
                    '&time_stamp=' + new Date().getTime()+
                    '&pagecount=&curPage={after}' ;

            }

            return url;

        };
        $scope.expert = new scrollPager01(getUrl());

        /*$scope.expert.callback = function(){

            var items = $scope.expert.items;
            for(var i = 0,len = items.length;i < len;i++){
                var item = items[i];
                if(item.doctormobile == $scope.mobile && $scope.filterStatus != 'E'){
                    item.isself = true;
                }
            }

        };*/

        $scope.search = function () {
            $scope.expert.items = [];
           /* $scope.expert.items = arr;*/
            $scope.expert.after = 1;
            $scope.expert.changeUrl(getUrl());
            $scope.expert.nextPage();
        };


        /*$scope.filterClick = function (code) {
            $scope.filterStatus = code;
            $scope.search();
        };*/

        $('.yxjt-filter li').on('touchstart',function(){

            $scope.filterStatus = $(this).attr('data-filterstatus');
            setTimeout(function(){
                $scope.search();
            },50)

        });


        $scope.toPlaying = function(item){

            item.status = $scope.filterStatus;

            if($scope.member){
                item.doctor_name = $scope.member.doctor_name
            }

            $cookies.remove('_playItem');

            $cookies.put('_playItem', JSON.stringify(item), {'expires': expireDate});
            var expireDate = new Date();
            expireDate.setDate(expireDate.getDate() + 1);
            if($scope.mobile == item.doctormobile && item.status != 'E'){
                //创建端
                window.location.href = item.teacherJoinUrl + '?token=' + item.teacherToken + '&nickname=' + item.mobile;

            }else{
                //观察者
                window.location.href = '/h5/#/ZbjtPlaying';

            }

        }

    }
);
ydylControllers.controller('ZbjtPlayingController',
    function($scope,$cookies, myHttp01, scrollPager01, controllerData) {

        $scope.member = controllerData.getMember(function (member) {
            $scope.member = member;
        });

        var ysjtPlayObj = JSON.parse($cookies.get('_playItem'));
        //console.log(ysjtPlayObj)
        //var ysjtPlayObj = {};

        var token =$cookies.get('memberToken');

        $scope.mobile =$cookies.get('memberMobile');

        $scope.doctor_name = ysjtPlayObj.doctor_name;

        $scope.directbroadcast_name = ysjtPlayObj.directbroadcast_name;

        $scope.isNotStateE = (ysjtPlayObj.status != 'E');

        //console.log($scope.isNotStateE)

        $scope.chat_desc = '';

        $scope.money = 5;

        $scope.filterIndex = 1;

        $scope.QAList = [];

        $scope.chatList = [];

        $scope.rewards = [];

        $scope.dialogType = '';//add success fail

        var getRewardUrl = function(){

            var url = 'SysDirectbroadcast/listTip' +
                '?directbroadcast_class_id=' + ysjtPlayObj.classId +
                '&finance_type=' + 3 +
                '&doctormobile=' + $scope.mobile +
                '&token=' + token +
                '&time_stamp=' + new Date().getTime() +
                '&pagecount=10000'+
                '&curPage={after}';


            return url;

        };

        $scope.rewards = new scrollPager01(getRewardUrl());
        $scope.getRewards = function(){
            $scope.rewards.items = [];
            /* $scope.expert.items = arr;*/
            $scope.rewards.after = 1;
            $scope.rewards.changeUrl(getRewardUrl());
            $scope.rewards.nextPage();
        };


        $('.zbjt-player-active>div').css({
            'min-height' : $(window).height() - 519
        });
        $('#doc_show_area').css({
            'height' : $(window).height() - 519
        });

        $scope.showFilter = function (type) {

            $scope.filterIndex = type;

        };
        $scope.liveCurPage = function(){

            javascript:history.back();

            return;

            swal({
                    title: "",
                    text: "确定要离开当前播放",
                    type: "",
                    showCancelButton: true,
                    confirmButtonColor: '#3f85df',
                    confirmButtonText: '离开',
                    cancelButtonText: '取消',
                    imageUrl: false
                },
                function(){
                    javascript:history.back();
                });

        };

       /* $('.input-radio').on('touchstart',function(){

            $('.input-radio').removeClass('_checked');

            $(this).addClass('_checked');

            $scope.selectedMethod =$(this).attr('data-selectedMethod');

        });*/

        $scope.money = '';

        $scope.changeMoney = function(money){

            if(money){
                $scope.money = money;
            }else{
                $scope.money = $scope.money.replace(/[^\d\.]/g,'');
            }

        };

        $scope.hidden = true;
        $scope.dialogType = '';

        $scope.setRewardDialogState =function(type){

            $scope.money = '';
            $scope.hidden = false;
            $scope.dialogType = type;

        };

        $scope.show = function () {
            $scope.hidden = false;
            scrollTo(0,0);
        };

        $scope.hide = function () {
            $scope.hidden = true;
        };


        $scope.addDs = function(){

            $scope.show();
            $scope.dialogType = 'add';

        };

        $scope.selectedMethod = 'balance';

        $scope.selectPay = function(type){

            $scope.selectedMethod = type;

        };

        $scope.pay = function () {

            if(!$scope.money){
                alert('请输入打赏金额');
                return;
            }

            //$scope.hidden = true;
            switch($scope.selectedMethod){
                case 'balance':
                    myHttp01.jsonp('SysDirectbroadcast/remainPayTip?doctormobile=' + $scope.mobile
                        + '&token=' + token
                        + '&time_stamp=' + new Date().getTime()
                        + '&money='+$scope.money

                        + '&classId='+ysjtPlayObj.classId
                        + '&curDoctorMobile='+$scope.mobile
                        + '&targetDoctorMobile='+ysjtPlayObj.doctormobile,

                        //+ '&consultid=' + $location.search().consultId,
                        function (result) {
                            if(result.ret == '1'){
                                $scope.getRewards();
                                $scope.dsSuccess();
                            }else{
                                $scope.dsFail();
                            }

                    });
                    break;
                case 'wechat':
                    myHttp01.jsonp('apiWeiXinTip/jsPay?doctormobile=' + $scope.mobile
                        + '&token=' + token
                        + '&time_stamp=' + new Date().getTime()
                        + '&money='+$scope.money
                        + '&targetmobile='+ysjtPlayObj.doctormobile
                        + '&directbroadcast_class_id='+ysjtPlayObj.classId,

                        //+'&consultid=' + $location.search().consultId,
                        
                        function (result) {
                            var onBridgeReady = function () {

                                WeixinJSBridge.invoke(
                                    'getBrandWCPayRequest', {
                                        "appId": result.items.appId,     //公众号名称，由商户传入
                                        "timeStamp": result.items.timeStamp,         //时间戳，自1970年以来的秒数
                                        "nonceStr": result.items.nonceStr, //随机串
                                        "package": result.items.package,
                                        "signType": result.items.signType,         //微信签名方式：
                                        "paySign": result.items.paySign //微信签名
                                    },
                                    function (res) {
                                        if (res.err_msg == "get_brand_wcpay_request:ok") {
                                            alert('支付成功');
                                            location.href = '#/ZbjtPlaying'
                                        }     // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
                                    }
                                );
                            };
                            if (typeof WeixinJSBridge == "undefined") {
                                if (document.addEventListener) {
                                    document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                                } else if (document.attachEvent) {
                                    document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                                    document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                                }
                            } else {
                                onBridgeReady();
                            }
                        }
                    );

                    break;
            }
        }

        $scope.dsSuccess = function(){

            $scope.dialogType = 'success';

        };
        $scope.dsFail = function(){

            $scope.dialogType = 'fail';

        };

        $scope.dsFail = function(){

            $scope.dialogType = 'fail';

        };


        $scope.addChat = function(isQA,receivData){

            var obj = {

                nickName : receivData.sender,
                content : receivData.content,
                isSend : false,
                photoImg : ''

            };


            if(isQA) {

                $scope.QAList.push(obj)

            }else{

                $scope.chatList.push(obj);

            }

        }


        $scope.sendChat = function(){


            var obj = {

                nickName : $scope.mobile,
                content : $scope.chat_desc,
                isSend : true,
                photoImg : ''

            };

            if($scope.filterIndex == 1  ) {

                $scope.QAList.push(obj)

                $scope.wg1.send("submitQuestion", {
                    "content" : $scope.chat_desc
                });
                setTimeout(function(){
                    $('.input-chat-desc').val('');
                    $scope.chat_desc = '';
                },100);

            }else{

                $scope.chatList.push(obj);

                $scope.wg1.send("submitChat", {
                    "content" : $scope.chat_desc

                });
                setTimeout(function(){
                    $('.input-chat-desc').val('');
                    $scope.chat_desc = '';
                },100);
            }

        }



        $(function() {
            //1. 根据组获得通讯通道

            var site = 'dr-h-dr.gensee.com';
            /*
            ysjtPlayObj.classid = 'ZvGg6LzQDw'
            ysjtPlayObj.studentClientToken = '939843'
            ysjtPlayObj.nickName = 'nickName';
            */
            var callMyFun = function(){

                if(ysjtPlayObj.status == 'E') {


                    $('.zbjt-player-area').append(
                            '<gs:video-vod id="videoComponent"' +

                            ' site="' + site + '"' +

                            ' ctx="training"' +

                            ' ownerid="' + ysjtPlayObj.coursewares_id + '"' +

                            ' authcode="' + ysjtPlayObj.coursewares_token + '"' +

                            ' uname="' + ysjtPlayObj.doctor_name  + '" />'
                    );


                }else{

                    $('.zbjt-player-area').append(
                            '<gs:video-live id="videoComponent"'+

                            ' site="' + site + '"' +

                            ' ctx="training"' +

                            ' ownerid="' + ysjtPlayObj.classId + '"' +

                            ' authcode="' + ysjtPlayObj.studentWebToken + '" ' +

                            ' uname="' + ysjtPlayObj.doctor_name + '" />'
                    );



                }



                $('#doc_show_area').append('<gs:doc id="docComponent" ' +

                    ' site="'+site+'" '+

                    ' ownerid="'+ysjtPlayObj.classId+'" />')


                if(ysjtPlayObj.status == 'E'){
                    GS.loadTag('video-vod', document.getElementsByTagName("gs:video-vod")[0]);
                }else{
                    GS.loadTag('video-live', document.getElementsByTagName("gs:video-live")[0]);
                }

                GS.loadTag('doc', document.getElementsByTagName("gs:doc")[0]);
                //GS.loadTag('video-vod', document.getElementsByTagName("gs:video-vod")[0]);


                $scope.wg1 = GS.createChannel();

                var evts = ["onVoteResult", "onVote", "onStop", "onPlay", "onPause", "onStart", "onUserOnline", "onUserLeave", "onUserJoin", "onUserList"
                    , "onLottery" , "onFile", "onTextWebcast", "onRollcall", "onKickOut", "onMessage", "onSetting", "onQAList", "onQARemove", "onVideoConfig"
                    , "onDocChange", "onUrlOpen", "onUpgradeRequired", "onModuleFocus", "onQA", "onUserUpdate", "onStatus", "onAPIError", "onSubmitUpgrade", "onPriChat"
                    , "onPublicChat", "onWebAudioInvite", "onWebAudioClose", "onNetSettings", "onTagAudio", "onQAHighlight", "onCancelHighlight", "onDataReady","onUserHost"
                    ,"onUserAsker","onClassMode","onWebVoiceStatus","onMute","onVideoShow","onLiveDemandStart","onWebVoiceInvite","onWebVoiceMicList","onThirdPartChat"
                    ,"onWebVoiceInfo","onAnswerSheet","onRoleStatus"];

               /* { "list": [ { "id": "abcd-efg-hi",
                    "question": "how are you?",
                    "submitor": "Tom", "answer":
                        "fine, thank you.",
                    "answerBy": "Jack", "submitTime": 9654123, "answerTime": 8795623 "qaownerId": 8735466234 },
                */

                if(ysjtPlayObj.status == 'E'){

                    //公聊天
                    $scope.wg1.bind("onChatHistory", function (event) {

                        for(var step = 0,len = event.data.list.length;step < len;step++){

                            $scope.addChat(false,event.data);

                        }
                        if(event.data.more){

                            $scope.wg1.send("submitChatHistory", {});
                        }



                    });


                    // 问答历史
                    $scope.wg1.bind("onQAList", function (event) {


                        var list = event.data.list;

                        for(var step = 0,len = list.length;step < len;step++){

                            //if(list[step].answerBy && list[step].answer){

                                $scope.addChat(true,{
                                    sender : list[step].submitor,
                                    content : list[step].question
                                });
                                $scope.addChat(true,{
                                    sender : list[step].answerBy,
                                    content : list[step].answer
                                });

                            //}


                        }
                        if(event.data.more){
                            $scope.wg1.send("submitQAList", {});
                        }

                    });


                    $scope.wg1.bind("onDataReady", function (event) {

                        $scope.wg1.send("submitQAList", {});

                    });


                }else{


                    //问答

                    $scope.wg1.bind("onQA", function (event) {

                        var data = event.data;

                        if(data.answerBy && data.answer){
                            $scope.addChat(true,{
                                sender : data.submitor,
                                content : data.question
                            });
                            $scope.addChat(true,{
                                sender : data.answerBy,
                                content : data.answer
                            });
                        }

                    });
                    setInterval(
                        function(){
                            //历史 问答情况
                            $scope.wg1.bind("onQAList", function (event) {});
                        },3000
                    );
                    //公聊天
                    $scope.wg1.bind("onPublicChat", function (event) {


                        $scope.addChat(false,event.data);

                    });

                    //私聊天
                    $scope.wg1.bind("onPriChat", function (event) {


                        $scope.addChat(false,event.data);

                    });


                }



                //系统消息
                $scope.wg1.bind("onMessage", function (event) {


                    $scope.addChat(false, {
                        sender : '系统提示：',
                        content : event.data.content
                    });

                });

                //系统消息 直播开启通知
                $scope.wg1.bind("onStart", function (event) {

                    $scope.addChat(false, {
                        sender : '系统提示：',
                        content : '直播开启通知'
                    });

                });

                //系统消息 直播暂停通知
                $scope.wg1.bind("onPause", function (event) {

                    $scope.addChat(false, {
                        sender : '系统提示：',
                        content : '直播暂停通知'
                    });

                });

                //系统消息  直播恢复通知
                $scope.wg1.bind("onPlay", function (event) {

                    $scope.addChat(false, {
                        sender : '系统提示：',
                        content : '直播恢复通知'
                    });

                });

                //系统消息  直播停止通知
                $scope.wg1.bind("onStop", function (event) {

                    $scope.addChat(false, {
                        sender : '系统提示：',
                        content : '直播停止通知'
                    });

                });

                /* //系统消息  收到点名通知
                 wg1.bind("onRollcall", function (event) {

                 addChat(false, {
                 sender : '系统提示：',
                 content : '点名通知'
                 });

                 });*/


                //被提出
                $scope.wg1.bind("onKickOut", function (event) {

                    var content = '您已被会议组织者踢出，或其他情况引起课堂中断。您可以刷新或重新进入。';
                    $scope.addChat(false, {
                        sender : '系统提示：',
                        content : content
                    });
                    swal({
                        title: "",
                        text: content ,
                        confirmButtonText : '关闭'
                    });

                });



            };


            var otherJScipt = document.createElement("script");
            otherJScipt = document.createElement("script");
            otherJScipt.setAttribute("type", "text/javascript");
            otherJScipt.setAttribute("src", "http://static.gensee.com/webcast/static/sdk/js/gssdk.js");
            document.getElementsByTagName("head")[0].appendChild(otherJScipt);//追加到head标签内


            //判断服务器
            if (navigator.userAgent.indexOf("IE") >= 0) {
                //IE下的事件
                otherJScipt.onreadystatechange = function () {
                    //IE下的判断，判断是否加载完成
                    if (otherJScipt && (otherJScipt.readyState == "loaded" || otherJScipt.readyState == "complete")) {
                        otherJScipt.onreadystatechange = null;
                        callMyFun();
                    }
                };
            }
            else {
                otherJScipt.onload = function () {
                    otherJScipt.onload = null;
                    callMyFun();
                };
            }
        })

    }
);

function checkLogin($cookies){
    if($cookies.get('memberToken')== undefined)
    {
        alert('对不起，请先登录');
        location.href='#/Login';
        return false;
    }
}

